//
//  TaskDetailViewController.m
//  BaishidaiKnight
//
//  Created by mac book on 2019/1/28.
//  Copyright © 2019年 sy. All rights reserved.
//

#import "TaskDetailViewController.h"
#import "TaskOrderTableViewCell.h"
#import "TaskMerchantTableViewCell.h"
#import "TaskEarningsTableViewCell.h"
#import "TaskButtonTableViewCell.h"

#define Cell_H  90.f/HEIGHT_6S_SCALE


@interface TaskDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listDataArray; // 外卖数据源


@property(nonatomic,strong) UIView* earningsView;
@property(nonatomic,strong) UIView* bottomView;



@property(nonatomic,strong) UILabel* merchantTitleLabel;


@property(nonatomic,strong) TaskModel *oneModel;
@property(nonatomic,strong) TaskModel *twoModel;

@end

@implementation TaskDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"订单详情";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    [self creatsubViews];
    
    
  

    
    [self queryData];
    
}


#pragma mark -  DataSource
-(void)queryData{
    
    TaskModel *itemModel = self.taskModel.items.firstObject;

    NSDictionary* arg = @{
                          @"ince":@"get_order_infos",
                          @"emp_id":[UserHandle shareInstance].userId,
                          @"main_id":itemModel.order_id
                          };
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"详情data = %@",data);
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            NSDictionary* emptyDict = [data objectForKey:@"order"];
            
            self.oneModel = [TaskModel mj_objectWithKeyValues:emptyDict];
            self.twoModel = self.oneModel.items.firstObject;
            
            self.listDataArray = [TaskModel mj_objectArrayWithKeyValuesArray:self.twoModel.foods];

            [self.tableView reloadData];
            
        }else{
            [self alertHUD:[data objectForKey:@"fail"]];
        }
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
    }];
    
    
}



-(void)creatsubViews{
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame),  CGRectGetHeight(self.view.frame) - NAVGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.showsVerticalScrollIndicator = NO;
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    
    [self.tableView registerClass:[TaskOrderTableViewCell class] forCellReuseIdentifier:@"TaskOrderTableViewCell"];
    [self.tableView registerClass:[TaskMerchantTableViewCell class] forCellReuseIdentifier:@"TaskMerchantTableViewCell"];
    [self.tableView registerClass:[TaskEarningsTableViewCell class] forCellReuseIdentifier:@"TaskEarningsTableViewCell"];
    [self.tableView registerClass:[TaskButtonTableViewCell class] forCellReuseIdentifier:@"TaskButtonTableViewCell"];

}

#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section ==1) {
        return self.listDataArray.count;

    }else{
        return 1;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section ==0) {
        return 90;

    }else if (indexPath.section ==2){
        
        return 70;

    }else if (indexPath.section ==3){
        return 55;
        
    }else{
        
        return Cell_H;
        
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section ==0) {

        TaskOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TaskOrderTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.taskModel = self.oneModel;
        
        return cell;
        
    }else if (indexPath.section ==1){
        
        TaskMerchantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TaskMerchantTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        TaskModel *model =  self.listDataArray[indexPath.row];
         cell.taskModel = model;
        
        return cell;
        
    }else if (indexPath.section ==2){
        
        TaskEarningsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TaskEarningsTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.taskModel = self.twoModel;

        return cell;

    }else{
        
        
        TaskButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TaskButtonTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isSend = self.isSend;
        cell.TaskButtonBlock = ^(NSInteger tag) {
            if (tag == 1001) {
                
                [self callPhone:self.twoModel.site_phone];
                
            }else if (tag == 1002){
                
                [self callPhone:self.twoModel.phone];
                
            }else{
                
                if (self.isSend) {
                    [self makeSureSendData];
                }else{
                 
                    [self makeSureGetData];
                }
                
            }
            
            
        };
        
        return cell;
        
    }

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (section == 1) {
        return 60;
    }else{
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        return 40;
    }else{
        return 0.001;
    }
    
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = [UIColor whiteColor];
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH, 40)];
        [headerView addSubview:title];
        title.textColor = kMyColor(113, 113, 113);
        title.font = kFontNameSize(15);
        
        
        title.text = self.twoModel.site_name;

        return headerView;
    }else{
        
        return nil;
        
    }

}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = [UIColor clearColor];

    if (section == 1) {
        
        UIView *back = [[UIView alloc] init];
        back.backgroundColor = [UIColor whiteColor];
        [footer addSubview:back];
        [back mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(footer);
            make.bottom.equalTo(footer).offset(-10);
        }];
        
        UIImageView *arrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_arrowright"]];
        [back addSubview:arrowImageView];
        [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerY.equalTo(back);
            make.right.equalTo(back).offset(-10);
            make.size.mas_equalTo(CGSizeMake(10, 15));
            
        }];

        UILabel *title = [[UILabel alloc] init];
        title.textColor = kMyColor(113, 113, 113);
        title.font = kFontNameSize(14);
        title.text = @"商家地址：";
        [back addSubview:title];
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.bottom.equalTo(back);
            make.left.equalTo(back).offset(10);
            make.width.mas_equalTo(80);

        }];
        
        UILabel *content = [[UILabel alloc] init];
        content.textColor = [UIColor darkGrayColor];
        content.font = kFontNameSize(14);
        content.numberOfLines = 0;
        content.lineBreakMode = NSLineBreakByCharWrapping;
        [back addSubview:content];
        [content mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(back);
            make.left.equalTo(title.mas_right);
            make.right.equalTo(arrowImageView.mas_left);

        }];
        content.userInteractionEnabled=YES;
        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTouchUpInside:)];
        [content addGestureRecognizer:labelTapGestureRecognizer];

        
        content.text = self.twoModel.site_addr;

    }
    
    
    return footer;

}

-(void) labelTouchUpInside:(UITapGestureRecognizer *)recognizer{
    
    [CommonUntils naviAddressWithDestination:self.twoModel.site_addr withLatitude:self.twoModel.latitude withLongitude:self.twoModel.longitude withController:self];
}

/**
 *  拨打电话
 *
 *  @param phoneNumber 号码
 */
- (void)callPhone:(NSString *)phoneNumber{
    
    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNumber];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];

}


//确认送达
-(void)makeSureSendData{
    
    [self showHUD];
    
    NSDictionary* arg = @{@"ince":@"qs_send_food",
                          @"emp_id":[UserHandle shareInstance].userId,
                          @"order_id":self.twoModel.order_id
                          
                          };
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            NSString *sucess = data[@"sucess"];
            [self hidHUD: sucess success:YES complete:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }else{
            [self hidHUD:[data objectForKey:@"fail"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
    }];
    
}

//确认取货
- (void)makeSureGetData {
    
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"qs_get_food",
                          @"order_id":self.twoModel.order_id,
                          @"emp_id":[UserHandle shareInstance].userId
                          
                          };
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            NSString *sucess = data[@"sucess"];
            [self hidHUD: sucess success:YES complete:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }else{
            [self hidHUD:[data objectForKey:@"fail"]];
        }
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
    }];
}




#pragma mark -  property package
- (NSMutableArray *)listDataArray
{
    if (!_listDataArray) {
        _listDataArray = @[].mutableCopy;
    }
    return _listDataArray;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
